import { _decorator, Component, find, Node } from 'cc';
import { BaseGuideCommand } from './BaseGuideCommand';
const { ccclass, property } = _decorator;

@ccclass('ClickGuideCommand')
export class ClickGuideCommand extends BaseGuideCommand {
    private resolve!: () => void;
    private reject!: (reason?: any) => void;
    private targetNode: Node | null = null;

    private timeoutId?: number;

    protected async run(): Promise<void> {
        console.log("【ClickGuideCommand】执行...");
        // 获取当前的小时、分钟和秒数
        const now = new Date();
        const hours = now.getHours();
        const minutes = now.getMinutes();
        const seconds = now.getSeconds();

        // 打印当前时间（时:分:秒）
        console.log(`输出当前时间： ${hours}:${minutes}:${seconds}`);
        return new Promise((resolve, reject) => {
            this.resolve = resolve;
            this.reject = reject;

            this.findTargetNode();

            this.timeoutId = setTimeout(() => {
                this.cleanup();
                reject(new Error(`点击目标节点超时：${this.stepConfig.path}`))
            }, this.stepConfig.waitForSecond*1000);
        })
    }


    private findTargetNode(): void {
        this.targetNode = find(this.stepConfig.path);

        if (this.targetNode) {
            this.setupClickListener();
        }
        else {
            this.scheduleRetry();
        }
    }

    private setupClickListener() {
        this.targetNode.on(Node.EventType.TOUCH_END, this.handleClick, this)
    }

    private handleClick() {
        console.log("输出点击了")
        this.cleanup();
        this.resolve();
    }

    private scheduleRetry(): void {
        // this.schedule(() => {
        //     this.findTargetNode();
        // }, 0.1);
    }

    private cleanup() {
        clearTimeout(this.timeoutId);
        if (this.targetNode) {
            this.targetNode.off(Node.EventType.TOUCH_END, this.handleClick, this);
        }
    }
}


